use std::{fs::{self, OpenOptions}, io::Write, path::Path};

use serde::{Deserialize, Serialize};


#[derive(Serialize, Deserialize, Clone)]
pub struct Tree {
    pub label:String,
    pub children:Vec<Tree>,
    pub file_id:String,
    pub path:String,
}

impl Default for Tree {
    fn default() -> Self {
        Self { label: Default::default(), children: Default::default(), file_id: Default::default(), path: Default::default() }
    }
}


pub fn get_tree(path: String) -> Vec<Tree> {

    let entries = match fs::read_dir(path) {
        Ok(file) => file,
        Err(e) => panic!("打开文件失败!: {}", e),
      };
    
    let mut list: Vec<Tree> = vec![];

    for entry in entries {
        let entry = match entry {
            Ok(e) => e,
            Err(e) => panic!("打开文件失败!: {}", e),
        };
        let path = entry.path();
        let mut tree = Tree::default();
        tree.label = path.file_name().unwrap().to_str().unwrap().to_string();
        tree.path = path.as_path().to_str().unwrap().to_string();

        if path.is_file() {
        } else if path.is_dir() {
            tree.children = get_tree(path.as_path().to_str().unwrap().to_string());
        }

        list.push(tree);
    }

    list
}



pub fn save_file(content: String, path: String) {
    let mut file = match OpenOptions::new()
        .write(true)
        .create(true)
        .open(path) {
            Ok(file) => file,
            Err(e) => panic!("打开文件失败!: {}", e),
        };
    match file.write_all(content.as_bytes()) {
        Ok(_) => println!("成功!"),
        Err(_) => println!("失败!"),
    }
}


pub fn creat_dir(path: String) {
    let dir_path = Path::new(&path);
    // 检查文件夹是否存在，如果不存在则创建
    if !dir_path.exists() {
        match fs::create_dir_all(dir_path) {
            Ok(_) => println!("成功!"),
            Err(_) => println!("失败!"),
        }
        println!("Directory created successfully.");
    } else {
        println!("Directory already exists.");
    }

}




#[test]
fn test() {
    let tt = get_tree("C:\\Users\\tjw1t\\Documents\\WXWork\\1688856868331709".to_owned());

    println!("{:?}", serde_json::to_string(&tt));
}